"""简化的错误处理器"""
import time
from .config import setup_logging

class ErrorHandler:
    """统一的错误处理器"""
    
    def __init__(self, max_retries=3, retry_delay=1.0):
        self.logger = setup_logging('Error')
        self.max_retries = max_retries
        self.retry_delay = retry_delay
        self.error_counts = {}
        self.last_errors = {}
    
    def log_error(self, error_type, error_message, context=None):
        """记录错误"""
        error_key = f"{error_type}:{context or 'general'}"
        
        # 增加错误计数
        self.error_counts[error_key] = self.error_counts.get(error_key, 0) + 1
        self.last_errors[error_key] = {
            'message': error_message,
            'timestamp': time.time(),
            'count': self.error_counts[error_key]
        }
        
        # 记录日志
        log_msg = f"[{error_type}] {error_message}"
        if context:
            log_msg += f" (Context: {context})"
        log_msg += f" (Count: {self.error_counts[error_key]})"
        
        self.logger.error(log_msg)
    
    def should_retry(self, error_type, context=None):
        """判断是否应该重试"""
        error_key = f"{error_type}:{context or 'general'}"
        count = self.error_counts.get(error_key, 0)
        
        should_retry = count < self.max_retries
        return should_retry
    
    def reset_error_count(self, error_type, context=None):
        """重置错误计数"""
        error_key = f"{error_type}:{context or 'general'}"
        if error_key in self.error_counts:
            del self.error_counts[error_key]
        if error_key in self.last_errors:
            del self.last_errors[error_key]
    
    def get_error_status(self, error_type=None, context=None):
        """获取错误状态"""
        if error_type:
            error_key = f"{error_type}:{context or 'general'}"
            return self.last_errors.get(error_key)
        return self.last_errors.copy()
    
    def handle_with_retry(self, func, error_type, context=None, *args, **kwargs):
        """带重试的函数执行"""
        error_key = f"{error_type}:{context or 'general'}"
        
        while True:
            try:
                result = func(*args, **kwargs)
                # 成功时重置错误计数
                self.reset_error_count(error_type, context)
                return result
            
            except Exception as e:
                self.log_error(error_type, str(e), context)
                
                if not self.should_retry(error_type, context):
                    raise e
                
                # 等待后重试
                time.sleep(self.retry_delay)
    
    def clear_all_errors(self):
        """清空所有错误记录"""
        self.error_counts.clear()
        self.last_errors.clear()
    
    def get_summary(self):
        """获取错误摘要"""
        if not self.error_counts:
            return "无错误记录"
        
        summary = []
        for error_key, count in self.error_counts.items():
            error_info = self.last_errors.get(error_key, {})
            summary.append(f"{error_key}: {count}次 (最后: {error_info.get('message', 'N/A')})")
        
        return "\n".join(summary)